package com.ht.managermentserver.security;

import com.ht.managermentserver.service.SysUserService;
import com.ht.managermentserver.utils.JwtTokenUtil;
import org.assertj.core.util.Strings;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author czy
 * @package com.ht.managermentserver.security
 * @date 2020/6/1 9:01
 */
public class JwtAuthenticationTokenFilter extends BasicAuthenticationFilter {

  //  SysUserService userService;

  public JwtAuthenticationTokenFilter(
      final AuthenticationManager authenticationManager, final SysUserService userService) {
    super(authenticationManager);
    //    this.userService = userService;
  }

  public JwtAuthenticationTokenFilter(
      final AuthenticationManager authenticationManager,
      final AuthenticationEntryPoint authenticationEntryPoint) {
    super(authenticationManager, authenticationEntryPoint);
  }

  @Override
  protected void doFilterInternal(
      final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain)
      throws IOException, ServletException {
    final String tokenHeader = request.getHeader(JwtTokenUtil.TOKEN_HEADER);

    // 如果请求头中没有Authorization信息则直接放行了
    if (tokenHeader == null || Strings.isNullOrEmpty(tokenHeader)) {
      chain.doFilter(request, response);
      return;
    }
    // 如果请求头中有token，则进行解析，并且设置认证信息
    //
    SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
    super.doFilterInternal(request, response, chain);
  }

  // 这里从token中获取用户信息并新建一个token
  private UsernamePasswordAuthenticationToken getAuthentication(final String tokenHeader) {

    if (JwtTokenUtil.verifyJwtToken(tokenHeader)) {

      try {
        final Long userId = JwtTokenUtil.getUserId(tokenHeader);

        // final SysUser sysUser = userService.getById(userId);

        return new UsernamePasswordAuthenticationToken(userId, null, new ArrayList<>());
      } catch (final Exception e) {
        e.printStackTrace();
      }
    }

    return null;
  }
}
